<template>
    <div>
        <Header/>
        <div class="table_container">
            <div class="search">
                <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                    <el-form-item label="用户名">
                        <el-input v-model="query.loginName" placeholder="用户名" @keyup.enter.native="getUsers()"></el-input>
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-select v-model="query.role" placeholder="角色" @change="getUsers">
                            <el-option label="学生" value="ROLE_student"></el-option>
                            <el-option label="教师" value="ROLE_teacher"></el-option>
                            <el-option label="管理员" value="ROLE_admin"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="学校">
                        <el-select v-model="query['school.id']"
                                   filterable remote
                                   reserve-keyword placeholder="请输入学校名称"
                                   :remote-method="searchSchool"
                                   :loading="searchForm.school.loading">
                            <el-option
                                v-for="item in searchForm.school.options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchUser">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
<!--            <el-table-->
<!--                :data="tableData"-->
<!--                highlight-current-row-->
<!--                style="width: 100%">-->
<!--                <el-table-column type="index" width="100"></el-table-column>-->
<!--                <el-table-column property="registerTime" label="注册日期" width="170px"></el-table-column>-->
<!--                <el-table-column property="loginName" label="用户名" width="150px"></el-table-column>-->
<!--                <el-table-column property="username" label="昵称" width="150px"></el-table-column>-->
<!--                <el-table-column property="school" width="200px" label="学校"></el-table-column>-->
<!--                <el-table-column property="role" width="100px" label="角色"></el-table-column>-->
<!--                <el-table-column label="操作" width="100">-->
<!--                    <template slot-scope="scope">-->
<!--                        <el-button @click="handleEditClick(scope.row)" type="text" size="small">编辑</el-button>-->
<!--                        <el-button @click="handlerUploadClick(scope.row)" type="text" size="small">上传头像</el-button>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--            </el-table>-->
            <el-table
                :data="tableData"
                style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-form label-position="left" inline class="demo-table-expand">
                            <el-form-item label="注册日期">
                                <span>{{ props.row.registerTime }}</span>
                            </el-form-item>
                            <el-form-item label="用户名">
                                <span>{{ props.row.loginName }}</span>
                            </el-form-item>
                            <el-form-item label="昵称">
                                <span>{{ props.row.username }}</span>
                            </el-form-item>
                            <el-form-item label="学校">
                                <span>{{ props.row.school }}</span>
                            </el-form-item>
                            <el-form-item label="角色">
                                <span>{{ props.row.role }}</span>
                            </el-form-item>
                            <el-form-item label="头像">
                                    <img v-if="props.row.image" :src="props.row.image" class="avatar">
                            </el-form-item>

                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column label="用户 ID" prop="id"></el-table-column>
                <el-table-column label="注册日期" prop="registerTime"></el-table-column>
                <el-table-column label="用户名" prop="loginName"></el-table-column>
                <el-table-column label="昵称" prop="username"></el-table-column>
                <el-table-column label="学校" prop="school"></el-table-column>
                <el-table-column label="角色" prop="role"></el-table-column>
                <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                        <el-button @click="handleEditClick(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="handlerUploadClick(scope.row)" type="text" size="small">头像</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="Pagination" style="text-align: left;margin-top: 10px;">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="count">
                </el-pagination>
            </div>
        </div>
        <!--    <Footer/>-->

        <el-dialog title="修改用户信息" :visible.sync="dialogFormVisible">
            <el-form  ref="editUserForm" :model="selectRow" :rules="rules">
                <el-form-item label="登录名" label-width="100px" prop="loginName" required>
                    <el-input v-model="selectRow.loginName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="昵称" label-width="100px" required>
                    <el-input v-model="selectRow.username" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" label-width="100px">
                    <el-input v-model="selectRow.password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="出生日期" label-width="100px">
                    <el-date-picker placeholder="选择时间" v-model="selectRow.registerTime"
                                    style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="用户角色" label-width="100px">
                    <el-select v-model="selectRow.role" placeholder="请选择">
                        <el-option label="学生" value="学生"></el-option>
                        <el-option label="教师" value="教师"></el-option>
                        <el-option label="管理员" value="管理员"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUser('editUserForm')">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="修改用户信息" :visible.sync="dialogImgFormVisible">
            <el-form  ref="uploadImgUserForm"  class="demo-table-expand">
                <el-form-item label="头像" >
                    <el-upload
                        action="123"  list-type="picture-card"
                        :http-request="upload"
                        :show-file-list="false"
                        :on-preview="handlePictureCardPreview"
                        :before-upload="beforeAvatarUpload"
                        :on-remove="handleRemove">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i class="el-icon-plus" ></i>
                    </el-upload>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
<!--                <el-button @click="dialogImgFormVisible = false">取 消</el-button>-->
<!--                <el-button type="primary" @click="updateImg('editUserForm')">确 定</el-button>-->
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Header from '@/components/Header'
    import Footer from '@/components/Footer'
    import {getUserCount, getUserList, isExistsLoginName, searchSchool, updateUser} from "../../api/getData";
    import dtime from "time-formater"

    export default {
        name: "UserList",
        data() {
            var validateLoginName = async (rule, value, callback) => {
                console.log(this.selectRow)
                if (!value) {
                    return callback(new Error('用户名不能为空'));
                }
                if(this.selectRow.thisloginName == value){
                    return true;
                }
                // 校验该用户名是否存在
                const isExists = await isExistsLoginName({loginName:value});
                if(isExists.data.data == true){
                    return callback(new Error('用户名已存在'));
                }
            };
            return {
                query: {page: 1, size: 5, loginName:''},
                tableData: [{
                    registerTime: '2016-05-02',
                    loginName: '王小虎',
                    username: 'admin',
                    school: '上海市普陀区金沙江路 1518 弄',
                    role: '学生'
                }, {
                    registerTime: '2016-05-04',
                    loginName: '王小虎',
                    username: 'admin',
                    school: '上海市普陀区金沙江路 1517 弄',
                    role: '教师'
                }],
                currentRow: null,
                pageSize:5,
                count: 0,
                currentPage: 1,

                dialogFormVisible: false,
                selectRow: {},

                searchForm: {
                    username: '',
                    school: {options: [], loading: false,}
                },
                rules:{
                    loginName:[{ validator: validateLoginName, trigger: 'blur' }],
                },
                // upload
                dialogImgFormVisible:false,
                imageUrl:'',
                editUserId:''
            }
        },
        components: {Header, Footer},
        created() {
            this.getUsers();
            // getUserInfo2();
        },
        watch: {
        },
        methods: {
            async initData() {
                try {
                    const countRes = await getUserCount();
                    if (countRes.status == 200) {
                        this.count = countRes.data.data;
                    }
                    this.getUsers();
                } catch (err) {
                    console.log('获取数据失败', err);
                }
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.query.page = this.currentPage;
                this.offset = (val - 1) * this.limit;
                this.getUsers()
            },
            handlerUploadClick(row){
                this.dialogImgFormVisible = true;
                this.imageUrl = row.image;
                this.editUserId = row.id;
            },
            async getUsers() {
                const countRes = await getUserCount(this.query);
                if (countRes.status == 200) {
                    this.count = countRes.data.data;
                }

                const Users = await getUserList(this.query);
                this.tableData = [];
                if(Users.data.data.content.length==0){
                    return;
                }
                Users.data.data.content.forEach(item => {
                    const tableData = {};
                    tableData.id = item.id;
                    tableData.loginName = item.loginName;
                    tableData.school = item.school?item.school.schoolName:'未知';
                    if (item.role == 'ROLE_teacher') {
                        tableData.role = '教师'
                    } else if (item.role == 'ROLE_student') {
                        tableData.role = '学生'
                    } else {
                        tableData.role = '管理员'
                    }
                    tableData.username = item.username;
                    if(item.image){
                        tableData.image = this.HOST + item.image;
                    }
                    tableData.registerTime = item.registerTime;
                    this.tableData.push(tableData);
                });
                this.selectRow = this.tableData[0]
            },
            async handleEditClick(row) {
                this.selectRow = row;
                this.selectRow.thisloginName = row.loginName;
                this.dialogFormVisible = true;
            },
            async updateUser(form) {
                this.$refs[form].validate(async (valid) => {
                    if (valid) {
                        console.log(this.selectRow);
                        this.selectRow.registerTime = dtime(this.selectRow.registerTime).format('YYYY/MM/DD')
                        const updateRes = await updateUser(this.selectRow)
                        console.debug(updateRes)
                        this.dialogFormVisible = false;
                    }
                });

            },
            async searchSchool(query) {  // 学校查询
                if(query==''){
                    return ;
                }
                this.searchForm.school.options = [];
                this.searchForm.school.loading = true;
                // lable: xx省xx市xx区 xx学校
                const Schools = await searchSchool({name:query})
                if(Schools.data.code == 0){
                    this.searchForm.school.options.push({value:0,
                        label: '全部'})
                    Schools.data.data.forEach(item =>{
                        this.searchForm.school.options.push({value:item.id,
                            label: item.provinceName+item.cityName+item.countyName+' '+ item.schoolName})
                    });
                }
                // this.searchForm.school.options = [{value: 1, label: 'ssss'}, {value: 2, label: 'ssss'},]
                this.searchForm.school.loading = false;
            },
            async searchUser() {
                // this.query.loginName = this.searchForm.loginName;
                // this.query.role = this.searchForm.role
                // 'school.id': this.searchForm.school,
                this.getUsers()
            },
            handleRemove(file, fileList) {
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            async upload(file, id) {
                console.log(file)
                console.log(id)
                const formData = new FormData();
                formData.append('file', file.file);
                formData.append('userId', this.editUserId);
                this.$http.post("/api/user/updateImg", formData, {headers:{'Content-Type':'multipart/form-data'}})
                    .then(res=>{
                        this.imageUrl = this.HOST  + res.data.data.image + "?aa=1";
                        this.$message('头像上传成功');
                    });
                this.dialogImgFormVisible = false;
            },
            beforeAvatarUpload(file){
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                // if (!isJPG) {
                //     this.$message.error('上传头像图片只能是 JPG 格式!');
                // }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isLt2M;
            },
        },
    }
</script>

<style scoped lang="less">
    .search {
        padding: 20px;
    }
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .avatar{
        width: 149px;
        height: 149px;
        float: left;
    }
</style>
